from flask import render_template, request,redirect
ffrom Web.Service import WebBaseService,XssService,SessionService,BBsService
from Web.Pojo.Post import Post
from Web.Pojo.User import User
from Web.Pojo.Message import Message
from flask.blueprints import Blueprint
from Web.Pojo.ViewObject import ViewObject
from Web.Pojo.ReplyToPost import ReplyToPost
from __init__ import db
from Web.Controller.__init__ import areas
import cgi,datetime,time
bbs = Blueprint('bbs', __name__)

class ViewObj:
    pass

########################################################
#                                                   主页
########################################################
@bbs.route("/")
@cache.cached(timeout=30,key_prefix='index')
def bbsIndex():
    viewObject = ViewObj()
    currentUser = SessionService.get("user")
    type = request.args.get( "order" )
    articleAndUserList = []
    topArticleListAndUser = []

    # articles list
    if type == "popular":
        articles = Post.query.order_by( Post.popularity.desc( ) ).limit( 20 )
        viewObject.type=type
    else:
        articles = Post.query.order_by( Post.id.desc( ) ).limit( 20 )
        viewObject.type = type
    for article in articles:
        user = User.query.filter(User.id == article.authorid).first()
        articleAndUserList.append(ViewObject(article,user))

    popularArticlesList = Post.query.order_by( Post.popularity.desc( ) )[ 0:10 ]


    # 置顶文章列表
    topArticleList = Post.query.filter( Post.topId == 0 ).order_by( Post.topId.desc( ) ).limit(5).all( )
    for article in topArticleList:
        user = User.query.filter(User.id == article.authorid).first()
        topArticleListAndUser.append(ViewObject(article,user))

    #是否显示签到按钮
    if currentUser!=None and (datetime.datetime.now( ).day == currentUser.lastsign.day):
        viewObject.todaysign=1
    else:
        viewObject.todaysign = 0

    #排行
    coinList = User.query.order_by(User.coin.desc())[0:12]


    return render_template( '/bbs/index.html' , posts= articleAndUserList,popularList=popularArticlesList,viewObject=viewObject,areas=areas,topArticleListAndUser=topArticleListAndUser,user=SessionService.get("user"),coinList=coinList)

@bbs.route("/case/case.html")
def bbsIndex2():
    return render_template( '/bbs/case/case.html')

########################################################
#                                                   页码页面
########################################################
@bbs.route("/area/<int:areano>/page/<int:pageno>/")
@cache.cached(timeout=30,key_prefix='page')
def bbsIndex6(areano,pageno):
    pageList = [ ]
    cansuList = [ ]
    type = request.args.get("order")
    numOfOnePage=10 #一页文章数
    topNumOfOnePage = 5  # 一页置顶文章上限
    topArticleList = None
    articleAndUserList = [ ]
    topArticleListAndUser =[]

    #首页板块号为0,不存在首页板块 不得往首页板块发文章
    if areano==0:
        redirect("/bbs")

    #置顶文章列表
    topArticleList = Post.query.filter( Post.topId == areano ).order_by( Post.topId.desc( ) ).limit( topNumOfOnePage ).all( )
    for article in topArticleList:
        user = User.query.filter(User.id == article.authorid).first()
        topArticleListAndUser.append(ViewObject(article,user))

    #正常文章列表
    if type=="popular":
        articles = Post.query.filter(Post.bankuai==areano).order_by(Post.popularity.desc()).offset(numOfOnePage*(pageno-1)).limit(numOfOnePage)
    else:
        articles = Post.query.filter(Post.bankuai==areano).order_by(Post.id.desc()).offset(numOfOnePage*(pageno-1)).limit(numOfOnePage)
    for article in articles:
        user = User.query.filter( User.id == article.authorid ).first( )
        articleAndUserList.append( ViewObject( article , user ) )
    popularArticlesList = Post.query.order_by( Post.popularity.desc())[ 0:10 ]

    #页码组件
    maxPageNum = int(Post.query.filter(Post.bankuai==areano).count()/10)+1
    for count,pageid in enumerate(range(pageno,maxPageNum+1)):
        if count<6:
            pageList.append(pageid)

    #viewobj
    vobj = ViewObj( )
    vobj.lastPage = pageno - 1
    vobj.currentPage = pageno
    vobj.nextPage = pageno + 1
    vobj.maxPageNum = maxPageNum
    vobj.type = type
    vobj.areano = areano
    vobj.argString = WebBaseService.argToString(request.args)

    return render_template( '/bbs/jie/pageno.html' , posts= articleAndUserList,popularList=popularArticlesList,topArticleListAndUser=topArticleListAndUser,pageList=pageList,viewObject=vobj,areas=areas,user=SessionService.get("user"))

########################################################
#                                                   详情页面
########################################################
@bbs.route("/post/<postid>/")
@cache.cached(timeout=300,key_prefix='post')
def bbsIndex7(postid):
    #postid = mysqlTool.defSql( postid )
    currentUser = SessionService.get( "user" )
    posts = Post.query.filter(Post.id==postid).all()
    replys = ReplyToPost.query.filter(ReplyToPost.linkPostId==postid).all()
    replyUserList=[]
    popularArticleAndUserList = []
    postUser = None

    #正文
    for post in posts:
        post.content=XssService.defxss(WebBaseService.jiexiToHtml(post.content))
        postUser = User.query.filter(User.id==post.authorid).first()
    #回复和用户组合列表
    for reply in replys:
        reply.content=XssService.defxss(WebBaseService.jiexiToHtml(reply.content))
        user = User.query.filter(User.id==reply.authorid).first()
        replyUserList.append(ViewObject(reply,user))

    #最受欢迎文章
    popularArticlesList = Post.query.order_by( Post.popularity.desc( ) )[ 0:10 ]

    # viewobj
    viewObject = ViewObj( )
    viewObject.replyNum =len(replys)
    viewObject.postUser = postUser
    if currentUser!=None and (currentUser.id == postUser.id or currentUser.level>200):
        viewObject.vitualauthor = 1
    if currentUser!=None and currentUser.level>200:
        viewObject.vitualadmin = 1


    return render_template( '/bbs/jie/detail.html' , posts=posts ,replyUserList = replyUserList, viewObject=viewObject,linkId = postid,popularList=popularArticlesList,areas=areas,user=SessionService.get("user"))

########################################################
#                                                    发布页面
########################################################
@bbs.route("/jie/add.html",methods=['GET'])
def postArticlePage1():
    currentUser = SessionService.get( "user" )

    #未登录阻止
    if currentUser!=None:
        return render_template( '/bbs/jie/add.html',areas=areas,user=currentUser)
    else:
        return redirect("bbs/user/login.html")

@bbs.route("/jie/add.html",methods=['POST'])
def postArticlePage2():
    currentUser = SessionService.get( "user" )

    # 未登录阻止
    if currentUser != None:
        if BBsService.getUserLastTalktimeDiffSec()<30:
            return "{\"status\":-1,\"msg\":\"\",\"code\":\"发布过快\"}"
        post= WebBaseService.requestParamToInstance( Post( ) , request.values.dicts[ 1 ] )
        post.authorid = currentUser.id
        db.session.add( post )
        #更新最后发帖时间
        currentUser.lasttalk = int(str(time.time( ))[:-8])
        SessionService.set( "user" , currentUser )
        User.query.filter( User.id == currentUser.id ).update( {User.lasttalk: currentUser.lasttalk} )

        return "{\"status\":0,\"msg\":\"\",\"code\":\"发布成功\"}"
    else:
        return "{\"status\":-1,\"msg\":\"\",\"code\":\"未登录\"}"



########################################################
#                                                   发布回复
########################################################
@bbs.route("/jie/reply/",methods=['POST'])
def postArticlePage3():
    currentUser = SessionService.get( "user" )

    #已登录
    if currentUser != None:
        if BBsService.getUserLastTalktimeDiffSec()<30:
            return "{\"status\":-1,\"msg\":\"\",\"code\":\"发布过快\"}"

        #增加回复记录
        replypost = WebBaseService.requestParamToInstance(ReplyToPost( ),request.values.dicts[ 1 ] )
        replypost.authorid=currentUser.id
        #replypost.lasttalk = time.time( )
        db.session.add(replypost)

        #更新最后发帖时间
        currentUser.lasttalk =int(str(time.time( ))[:-8])
        SessionService.set( "user" , currentUser )
        User.query.filter( User.id == currentUser.id ).update( {User.lasttalk: currentUser.lasttalk} )

        #增加消息记录通知作者
        article = Post.query.filter(Post.id == replypost.linkPostId).first()
        message = Message()
        message.senderid = currentUser.id
        message.recverid = article.authorid
        message.msg=currentUser.nickname+" 回复了你的帖子 《"+article.title+"》"
        message.msglink = "/bbs/post/"+str(article.id)
        message.time = datetime.datetime.now()
        if message.senderid!=message.recverid:
            db.session.add( message )

        return "{\"status\":0,\"msg\":\"\",\"code\":\"发布成功\"}"
    # 未登录阻止
    else:
        return "{\"status\":-1,\"msg\":\"\",\"code\":\"未登录\"}"

if __name__ == '__main__':
    print("(bankuai,title,content) VALUES ('99','‘11’',''1' <a herf='http://127.0.0.1:5000/bbs/jie/add.html'> '".replace("\'","\\'"))
    print(replaceToHtml("(bankuai,title,content) VALUES ('99','‘11’',''1' <a herf='http://127.0.0.1:5000/bbs/jie/add.html'> ')"))
